package com.feng.cloud.auth.service.impl;

import com.feng.cloud.auth.entity.AuthUser;
import com.feng.cloud.auth.mapper.SystemUserMapper;
import com.feng.cloud.common.constants.auth.AuthConstant;
import com.feng.cloud.system.entity.SystemUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @ClassName FengUserDetailsService
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/5 18:44
 * @Version 1.0
 **/
@Service
@RequiredArgsConstructor
public class FengUserDetailsService implements UserDetailsService {

    private final SystemUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUser systemUser = userMapper.findByName(username);
        if(systemUser == null){
            //如果用户查不到，必须抛出异常，不能由provider来抛出异常,否则异常翻译失败
            throw new UsernameNotFoundException("userDetails is null");
        }
        boolean notLocked = AuthConstant.STATUS_VALID == systemUser.getStatus();
        //根据用户的id查询用户的权限
        String permissions = null;
        List<String> permissionList = userMapper.findPermissionStrListByUserId(systemUser.getUserId());
        if (!CollectionUtils.isEmpty(permissionList)) {
            permissions = String.join(",", permissionList);
        }
        AuthUser authUser = new AuthUser(systemUser.getUsername(), systemUser.getPassword(), true, true, true, notLocked,
                AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
        BeanUtils.copyProperties(systemUser, authUser);
        return authUser;
    }
}
